package com.lcf.system.service.impl;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.lcf.framework.constant.SysConstant;
import com.lcf.framework.exception.SysException;
import com.lcf.framework.utils.UserUtils;
import com.lcf.system.dao.SysUserDao;
import com.lcf.system.dto.user.LoginDTO;
import com.lcf.system.dto.user.OpenSafeDTO;
import com.lcf.system.entity.SysUser;
import com.lcf.system.enums.UserStatusEnum;
import com.lcf.system.service.AuthService;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 用户表(User)表服务实现类
 *
 * @author lcf
 * @since 2025-02-19 13:27:56
 */
@Service("authService")
public class AuthServiceImpl extends ServiceImpl<SysUserDao, SysUser> implements AuthService {
    @Override
    public SaTokenInfo login(LoginDTO login) {
        SysUser user = Db.lambdaQuery(SysUser.class)
                .eq(SysUser::getUsername, login.getUsername())
                .eq(SysUser::getPassword, UserUtils.passwordEncrypt(login.getPassword()))
                .one();

        if (user == null) {
            throw new SysException("账号或密码错误!");
        }
        if (!Objects.equals(user.getId(), SysConstant.PLATFORM_ADMIN_ID) && !Objects.equals(user.getStatus(), UserStatusEnum.PASS.getCode())) {
            throw new SysException("用户审核中或审核未通过");
        }

        //登录
        StpUtil.login(user.getId());

        return StpUtil.getTokenInfo();
    }

    @Override
    public void openSafe(OpenSafeDTO openSafe) {
        SysUser sysUser = Db.lambdaQuery(SysUser.class).select(SysUser::getPassword).eq(SysUser::getId, UserUtils.getUserId()).one();

        if (!Objects.equals(sysUser.getPassword(), UserUtils.passwordEncrypt(openSafe.getPassword()))) {
            throw new SysException("密码错误!");
        }

        // 密码正确，为当前会话打开二级认证，有效期为120秒
        StpUtil.openSafe(120);
    }
}

